import axios from 'axios';

axios.defaults.baseURL = 'http://127.0.0.1:8000'; // 更新API地址
axios.defaults.withCredentials = true; // 跨域携带cookie

const wsUrl = '127.0.0.1:8000/ws'

const accessToken = localStorage.getItem('Token');

const deepseekKey = 'sk-83a4a32f7cd14633b6c13b1e59ff3526';
const deepseekUrl = 'https://api.deepseek.com';

const api = {

    refreshToken(refreshToken) {
        return axios.post('/api/auth/refresh/', { refreshToken });
    },

    login(body) {
        return axios.post('/api/auth/login/', body);
    },
    register(body) {
        return axios.post('/api/auth/register/', body);
    },
    getChatRooms() {
        return axios.get('/api/chatroom/', {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        });
    },

    getChatRoomDetails(roomId) {
        return axios.get(`/api/chatroom/detail/${roomId}/`, {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        });
    },

    createChatRoom(body) {
        return axios.post('/api/chatroom/', body, {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        });
    },

    fetchChatMessages(roomId) {
        return axios.get(`/api/chatroom/${roomId}/message/`, {
            headers: {
                Authorization: `Bearer ${accessToken}`
            }
        });
    },

    // Deepseek

    createChatCompletion(messages) {
        const requestBody = {
            messages: messages.map(msg => ({
                content: msg.content,
                role: msg.isMine ? 'user' : 'system'
            })),
            model: 'deepseek-chat',
            max_tokens: 2048,
            temperature: 1
        };
        return axios.post(`${deepseekUrl}/chat/completions`, requestBody, {
            headers: {
                'Authorization': `Bearer ${deepseekKey}`,
                'Content-Type': 'application/json'
            }
        });
    },


    // WebSocket
    connectWebSocket(roomId) {
        const socket = new WebSocket(`ws://${wsUrl}/chatroom/${roomId}/`);
        socket.onopen = () => {
            console.log('WebSocket connected');
        };
        return socket;
    },

    sendMessage(socket, roomId, userId, content) {
        socket.send(JSON.stringify({
            roomId: roomId,
            userId: userId,
            content: content
        }));
    },

};

export default api;
